<template>
  <div class="search-container">
    <form action="/">
      <van-search
        v-model="searchText"
        show-action
        placeholder="请输入搜索关键词"
        background="#4998f5"
        @search="onSearch"
        @cancel="onCancel"
        class="search-form"
        @clear="isResultShow = false"
        @input="onInput"
      />
    </form>

    <!-- 搜索结果 -->
    <search-result v-if="isResultShow" :search-text="searchText" />
    <!-- /搜索结果 -->

    <!-- 联想建议 -->
    <search-suggestion
      v-else-if="searchText"
      :search-text="searchText"
      @search="onSearch"
    />
    <!-- /联想建议 -->

    <!-- 搜索历史记录 -->
    <search-history
      v-else
      :search-history="searchHistory"
      @search="onSearch"
      @clearHistories="searchHistory = []"
    />
    <!-- /搜索历史记录 -->
  </div>
</template>

<script>
import SearchResult from './components/search-result'
import SearchHistory from './components/search-history'
import SearchSuggestion from './components/search-suggestion'
import { setItem, getItem } from '@/utils/storage'
export default {
  name: 'SearchPage',
  components: {
    SearchResult,
    SearchHistory,
    SearchSuggestion
  },
  props: {},
  data () {
    return {
      searchText: '', // 绑定输入框内容
      isResultShow: false, // 控制搜索结果列表的显示和隐藏
      searchHistory: getItem('HISTORIES-LIST') || [] // 保存历史记录
    }
  },
  computed: {},
  watch: {
    searchHistory (val) {
      console.log(val)
      setItem('HISTORIES-LIST', val)
    }
  },
  created () {},
  methods: {
    onSearch (val) {
      this.searchText = val

      // 判断是否存在 不能重复
      const index = this.searchHistory.indexOf(val)
      if (index !== -1) {
        this.searchHistory.splice(index, 1)
      }
      // 在 历史记录数组 前面添加
      this.searchHistory.unshift(val)

      this.isResultShow = true
    },
    onCancel () {
      this.$router.back()
    },

    onInput () {
      if (!this.searchText) {
        this.isResultShow = false
      }
    }
  }
}
</script>

<style lang="less" scoped>
.search-container {
  padding-top: 108px;
  .van-search__action {
    color: #fff;
  }
  .search-form {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    z-index: 1;
  }
}
</style>
